package cn.yudao;

import cn.yudao.utils.ESClientUtil;
import org.apache.lucene.queryparser.flexible.standard.QueryParserUtil;
import org.elasticsearch.action.bulk.BulkRequestBuilder;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.delete.DeleteRequestBuilder;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetRequestBuilder;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequestBuilder;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.update.UpdateRequestBuilder;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.sort.SortOrder;
import org.junit.Test;
import sun.plugin2.message.JavaScriptToStringMessage;

import java.util.HashMap;
import java.util.Map;

public class estest {


    /**
    * @Title: test
    * @Description: 新增测试
    * @Author: Mr.Jia
    * @Version: 1.0
    * @Date:  2022/7/24 19:57
    * @Parameters:
    * @Return
    */
    @Test
    public void testAdd() throws Exception{
       // 获取es对象
        TransportClient client = ESClientUtil.getClient();
        // 获取新增对象
        IndexRequestBuilder indexRequestBuilder = client.prepareIndex("pethome", "pet", "1");
        // 创建一个map集合，放入我们需要存储的值
        Map<String, Object> map = new HashMap<>();
        map.put("id",1);
        map.put("name","李多");
        IndexResponse indexResponse = indexRequestBuilder.setSource(map).get();
        System.out.println(indexResponse);
        client.close();
    }


    /**
    * @Title:
    * @Description: 查询测试
    * @Author: Mr.Jia
    * @Version: 1.0
    * @Date:  2022/7/24 19:58
    * @Parameters:
    * @Return
    */
    @Test
    public void testGet() throws Exception{
        // 获取es连接
        TransportClient client = ESClientUtil.getClient();
        // 获取查询对象
        GetRequestBuilder getRequestBuilder = client.prepareGet("pethome", "user", "1");
        GetResponse documentFields = getRequestBuilder.get();
        System.out.println(documentFields);
        client.close();
    }

    /**
    * @Title: test
    * @Description: 删除数据
    * @Author: Mr.Jia
    * @Version: 1.0
    * @Date:  2022/7/24 20:00
    * @Parameters:
    * @Return
    */
    @Test
    public void testRem() throws Exception{
// 获取es连接
        TransportClient client = ESClientUtil.getClient();
        // 获取删除对象
        DeleteRequestBuilder deleteRequestBuilder = client.prepareDelete("pethome", "pet", "1");
        DeleteResponse deleteResponse = deleteRequestBuilder.get();
        System.out.println(deleteResponse);
        client.close();
    }

    /**
    * @Title: testUpt
    * @Description: 修改数据
    * @Author: Mr.Jia
    * @Version: 1.0
    * @Date:  2022/7/24 20:02
    * @Parameters:
    * @Return
    */
    @Test
    public void testUpt() throws Exception{
        // 获取es连接
        TransportClient client = ESClientUtil.getClient();
        // 获取删除对象
        UpdateRequestBuilder updateRequestBuilder = client.prepareUpdate("pethome", "pet", "1");
        // 创建一个map集合，放入我们需要存储的值
        Map<String, Object> map = new HashMap<>();
        map.put("id",1);
        map.put("name","王刚");
        updateRequestBuilder.setDoc(map);
        UpdateResponse updateResponse = updateRequestBuilder.get();
        System.out.println(updateResponse);
        client.close();
    }





    /**
     * @Description: 批量添加数据
     * @Author: 笔上人间
     * @Date: 2022/7/23 0:02
     * @return: void
     **/
    @Test
    public void testBatch() throws Exception {
        // 1.获取ES连接
        TransportClient client = ESClientUtil.getClient();
        // 2.创建批量操作对象
        BulkRequestBuilder bulk = client.prepareBulk();
        // 3.批量创建文档，放入批量操作对象中
        for (int i = 2; i < 100; i++) {
            IndexRequestBuilder builder = client.prepareIndex("pethome", "user", i + "").setSource(
                    XContentFactory.jsonBuilder()
                            .startObject()
                            .field("id", i - 1)
                            .field("name", "我在源码学习Java!" + i)
                            .field("age", i - 1)
                            .field("sex", i%2)
                            .endObject()
            );
            BulkResponse result = bulk.add(builder).get();
            System.out.println(result.status());
        }
        // 4.关闭连接
        client.close();
    }


    // - 查询用户表
    //- name包含：我在源码
    //- age在1~12之间
    //- 每页大小2
    //- 从二页开始查
    //- 按照age倒序
    //- sex=1

    @Test
    public void test() throws Exception{
        // 1.获取连接对象通过工具类
        TransportClient client1 = ESClientUtil.getClient();
        // 获取到当前索引
        SearchRequestBuilder pethome1 = client1.prepareSearch("pethome");
        // 获取到类型
        SearchRequestBuilder user1 = pethome1.setTypes("user");
        // 根据类型对象设置查询规则
        //- 每页大小2
        user1.setSize(2);
        //- 从二页开始查
        user1.setFrom(2);
        //- 按照age倒序
        user1.addSort("age",SortOrder.DESC);
        // 因为user调用query时需要传入一个QueryBuilder对象,因为我们的条件语句需要写在query中，我们首先获取query对象、
        // 获取到BoolQueryBuilder对象因为我们需要使用DSL查询和DSL过滤
        BoolQueryBuilder boolQueryBuilder1 = QueryBuilders.boolQuery();
        //- name包含：我在源码
        boolQueryBuilder1.must(QueryBuilders.matchQuery("name","我在源码"));
        //- age在1~12之间  sex=1
        boolQueryBuilder1.filter(QueryBuilders.rangeQuery("age").gte(1).lte(12)).filter(QueryBuilders.termQuery("sex",1));
        // 将当前querybuilder对象放入到类型对象的setquery中
        SearchRequestBuilder searchRequestBuilder1 = user1.setQuery(boolQueryBuilder1);
        // 因为数据在返回的hits中,有因为查询的结构，所以我们需要调用2此getHits方法
        SearchHit[] hits1 = searchRequestBuilder1.get().getHits().getHits();
        for (SearchHit documentFields : hits1) {
            System.out.println(documentFields);
        }

//======================================================================================================
        // 获取连接对象
        TransportClient client = ESClientUtil.getClient();
        // 创建获取es索引的对象
        SearchRequestBuilder pethome = client.prepareSearch("pethome");
        // 获取类型对象
        SearchRequestBuilder user = pethome.setTypes("user");
        // 增加判断条件每页大小为2
        user.setSize(2);
        //- 从二页开始查
        user.setFrom(2);
        //- 按照age倒序
        user.addSort("age", SortOrder.DESC);
        //- name包含：我在源码
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        boolQueryBuilder.must(QueryBuilders.matchQuery("name","我在源码"));
        //- age在1~12之间
        boolQueryBuilder.filter(QueryBuilders.rangeQuery("age").gte(1).lte(12));
        //- sex=1
        boolQueryBuilder.filter(QueryBuilders.termQuery("sex",1));
        // 将定制规则给user
        SearchRequestBuilder searchRequestBuilder = user.setQuery(boolQueryBuilder);
        SearchResponse searchResponse = searchRequestBuilder.get();
        SearchHit[] hits = searchResponse.getHits().getHits();
        for (SearchHit hit : hits) {
            System.out.println(hit);
        }
    }
}
